package com.imooc.mall.controller;

import com.github.pagehelper.PageInfo;
import com.imooc.mall.common.ApiRestResponse;
import com.imooc.mall.common.Constant;
import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.pojo.Product;
import com.imooc.mall.model.request.AddProductReq;
import com.imooc.mall.model.request.UpdateProductReq;
import com.imooc.mall.service.ProduceService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.UUID;

/**
 * 后台商品管理Controller
 */
@Controller
public class ProductAdminController {

    @Autowired
    private ProduceService produceService;
    /**
     * 添加商品
     */
    @ApiOperation("管理员新增商品")
    @PostMapping("admin/product/add")
    @ResponseBody

    public ApiRestResponse addProduct(@Valid @RequestBody AddProductReq addProductReq){
        produceService.addProduct(addProductReq);
        return ApiRestResponse.success();
    }
    /**
     * 图片上传
     */
    @ApiOperation("管理员上传图片")
    @PostMapping("admin/upload/file")
    @ResponseBody
    public ApiRestResponse upload(HttpServletRequest httpServletRequest,
                                  @RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称UUID
        UUID uuid = UUID.randomUUID();
        String newFileName = uuid.toString() + suffixName;
        //创建文件
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new ImoocMallException(ImoocMallExceptionEnum.MKDIR_FAILED);
            }
        }
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return ApiRestResponse
                    .success(getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/images/"
                            + newFileName);
        } catch (URISyntaxException e) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.UPDATE_FAILED);
        }
    }

    private URI getHost(URI uri) {
        URI effectiveURI;
        try {
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
                    null, null, null);
        } catch (URISyntaxException e) {
            effectiveURI = null;
        }
        return effectiveURI;
    }

    /**
     * 更新商品功能
     */
    @PostMapping("/admin/product/update")
    @ResponseBody
    @ApiOperation("修改商品功能的接口")
    public ApiRestResponse updateProduct(@Valid @RequestBody UpdateProductReq updateProductReq){
        Product product = new Product();
        BeanUtils.copyProperties(updateProductReq,product);
        produceService.update(product);
        return ApiRestResponse.success();
    }

    /**
     * 根据id删除商品的功能
     */
    @PostMapping("/admin/product/delete")
    @ResponseBody
    @ApiOperation("删除商品功能的接口")
    public ApiRestResponse deleteProductById(@RequestParam Integer id){

        produceService.deleteProductById(id);
        return ApiRestResponse.success();
    }

    /**
     * 商品批量上下架
     */
    @PostMapping("/admin/product/bathUpdateSellStatus")
    @ResponseBody
    @ApiOperation("统一上下架管理")
    public ApiRestResponse bathUpdateSellStatus(@RequestBody @RequestParam Integer[] ids,
                                                @RequestBody @RequestParam Integer sellStatus){

        produceService.bathUpdateSellStatus(ids,sellStatus);
        return ApiRestResponse.success();
    }


    /**
     * 后台商品列表接口
     */
    @ApiOperation("后台商品展示")
    @GetMapping("/admin/product/list")
    @ResponseBody
    public ApiRestResponse list(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize){
        PageInfo pageInfo = produceService.listForAdmin(pageNum, pageSize);
       return ApiRestResponse.success(pageInfo);

    }


}
